package com.zhoujie.roomdemo.presenter.impl;

import android.text.TextUtils;
import android.util.Log;

import com.zhoujie.roomdemo.db.AppDatabase;
import com.zhoujie.roomdemo.db.User;
import com.zhoujie.roomdemo.db.UserDao;
import com.zhoujie.roomdemo.presenter.ILoginPresenter;
import com.zhoujie.roomdemo.util.AppExecutors;
import com.zhoujie.roomdemo.view.ILoginCallback;

import java.util.List;

public class LoginPresenterImpl implements ILoginPresenter {

    private final UserDao mUserDao;
    private final AppExecutors mAppExecutors;
    private ILoginCallback mCallback;
    private int click = 0;//保证只能触发登录一次
    private static final String TAG = "登录";

    public LoginPresenterImpl() {
        mUserDao = AppDatabase.getDatabase().mUserDao();
        mAppExecutors = AppExecutors.getAppExecutors();
        getAccountAutoCompleteData();
    }

    @Override
    public void login(String account, String pwd) {
        if (click == 0) {
            saveLogin(account, pwd);
            click++;
            mCallback.onSuccess();
        }
    }

    @Override
    public void saveLogin(final String account, final String pwd) {
        mAppExecutors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {
                User user = new User();
                user.account = account;
                user.pwd = pwd;
                Log.d("登录", "插入: " + user);
                mUserDao.insertUser(user);
                getAccountAutoCompleteData();
            }
        });
    }

    @Override
    public void getAccountAutoCompleteData() {
        mAppExecutors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {
                List<String> list = mUserDao.getAllAccount();
                Log.d(TAG, "查询所有账号: " + list);
                if (list != null && list.size() > 0) {
                    mCallback.onAutoCompleteTextGet(list);
                }
            }
        });
    }

    @Override
    public void getPwdByAccount(final String account) {
        if (!TextUtils.isEmpty(account)) {
            mAppExecutors.getDiskIO().execute(new Runnable() {
                @Override
                public void run() {
                    final String pwd = mUserDao.getPwdByAccount(account);
                    Log.d(TAG, "pwd: " + pwd);
                    if (!TextUtils.isEmpty(pwd)) {
                        mAppExecutors.getMainThread().execute(new Runnable() {
                            @Override
                            public void run() {
                                mCallback.onClickAutoAccount(pwd);
                            }
                        });
                    }
                }
            });
        }
    }

    @Override
    public void registerCallback(ILoginCallback callback) {
        mCallback = callback;
    }

    @Override
    public void unregisterCallback(ILoginCallback callback) {
        callback = null;
    }
}
